﻿using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Text;
using IntelligentGateway.SmartCommunity.BUS;
using IntelligentGateway.SmartCommunity.Model;
using IntelligentGateway.SmartCommunity.DAL;

namespace IntelligentGateway.SmartCommunity.DevicePlatform
{
    public class RaspberryPie
    {
        public void RunCommand(string command)
        {
            Process.Start("sudo", command);
        }

        public NetInfo GetJMNetInfo()
        {
            NetInfo netInfo = new NetInfo();
            try
            {
                StreamReader reader = new StreamReader(@"/etc/netplan/01-network-manager-all.yaml", Encoding.Default);
                string theReply = reader.ReadToEnd();
                reader.Close();
                Regex strRegex = new Regex(@"(?<str>([^\w\s]+|\s*)enp1s0:\s*dhcp4: no([\w\W]*))");
                Regex addressRegex = new Regex(@"([^\w\s]+|\s*)addresses:\s*[^\w\s](?<address>\d+.\d+.\d+.\d+/\d+)]\s*");
                Regex gatewayRegex = new Regex(@"(?<gateway>([^\w\s]+|\s*)via:\s*\d+.\d+.\d+.\d+)\s*");
                Regex maskReg = new Regex(@"\d+.\d+.\d+.\d+/(?<mask>\d+)\s*");
                Regex ipRegex = new Regex(@"\s*(?<ip>\d+.\d+.\d+.\d+)\s*");

                MatchCollection strCollection = strRegex.Matches(theReply);

                if (strCollection.Count > 0)
                {
                    string str_value = strCollection[0].Groups["str"].Value;
                    MatchCollection addressCollection = addressRegex.Matches(str_value);
                    MatchCollection routerCollection = gatewayRegex.Matches(str_value);
                    for (int i = 0; i < addressCollection.Count; i++)
                    {
                        string str = addressCollection[i].Groups["address"].Value.Trim();
                        string ip = ipRegex.Matches(str)[0].Groups["ip"].Value.Trim();
                        netInfo.IP = ip;
                        int mask = Convert.ToInt32(maskReg.Matches(str)[0].Groups["mask"].Value.Trim());
                        string Mask = GetMask(mask);
                        netInfo.Mask = Mask;
                    }

                    for (int i = 0; i < routerCollection.Count; i++)
                    {
                        string str = routerCollection[i].Groups["gateway"].Value.Trim();
                        string ip = ipRegex.Matches(str)[0].Groups["ip"].Value.Trim();
                        netInfo.Router = ip;
                    }
                }

                return netInfo;
            }
            catch (Exception ex)
            {
                SmartCommunityLogHelper.Log(ex.ToString());
                return netInfo;
            }
        }

        public string GetMask(int value)
        {
            try
            {
                string str = string.Empty;
                for (int i = 0; i < value; i++)
                {
                    str += "1";
                }
                str = str.PadRight(32, '0');
                string a = Convert.ToInt32(str.Substring(0, 8), 2).ToString() + "." + Convert.ToInt32(str.Substring(8, 8), 2).ToString() + "." + Convert.ToInt32(str.Substring(16, 8), 2).ToString() + "." + Convert.ToInt32(str.Substring(24, 8), 2).ToString();
                return a;
            }
            catch
            {
                return "0.0.0.0";
            }
        }

        public bool UpdateJMNetInfo(NetInfo netInfo)
        {
            try
            {
                using (FileStream fileStream = new FileStream("/etc/netplan/01-network-manager-all.yaml", FileMode.Open, FileAccess.Write, FileShare.Write))
                {
                    fileStream.Seek(0, SeekOrigin.Begin);
                    fileStream.SetLength(0);
                    using (StreamWriter streamWriter = new StreamWriter(fileStream))
                    {
                        streamWriter.WriteLine("network:");
                        streamWriter.WriteLine("  version: 2");
                        streamWriter.WriteLine("  renderer: NetworkManager");
                        streamWriter.WriteLine("  ethernets:");
                        streamWriter.WriteLine("    enp2s0:");
                        streamWriter.WriteLine("      dhcp4: yes");
                        streamWriter.WriteLine("    enp1s0:");
                        streamWriter.WriteLine("      dhcp4: no");
                        streamWriter.WriteLine("      addresses: [" + netInfo.IP + "/" + netInfo.Mask + "]");
                        streamWriter.WriteLine("      routes:");
                        streamWriter.WriteLine("        - to: 0.0.0.0/0");
                        streamWriter.WriteLine("          via: " + netInfo.Router);
                        streamWriter.WriteLine("          metric: 150");
                        streamWriter.WriteLine("      optional: true");
                        fileStream.Flush();
                        streamWriter.Close();
                    }

                    fileStream.Close();
                }
                RunCommand("netplan apply");
                RunCommand("reboot");
                return true;
            }
            catch (Exception ex)
            {
                SmartCommunityLogHelper.Log(ex.ToString());
                return false;
            }
        }
    }
}
